<template>
  <div>
    <div v-for="(materialCheckItem,index) in checkList"
         :key="index"
         style="position: relative;border: 1px solid #ddd;padding: 5px;border-radius: 5px;margin-bottom: 10px;"
    >
      <div style="position: absolute;top: -5px;right: -5px">
        <svg-icon icon-class="close-circle"
                  style="font-size: 20px;color: red;"
                  v-if="computed_show_close"
                  @click.native="()=>triggerDeleteDlt(materialCheckItem,index)"></svg-icon>
      </div>
      <receiving_materialcheck_with_materialitem_and_dltCom
          :props_edit="edit"
          :props_show_close="$props.props_show_close"
          :props_devel-material-item-dtl="materialCheckItem?.develMaterialDtl"
          :props_devel-material-item="materialCheckItem?.develMaterial"
          :props_devel-material-check="materialCheckItem"
          :props_billingType="formData?.billingType"
          :props_materialReceivingDtl="materialCheckItem?.materialReceivingDtl"
          @updatechange="()=>{
                         $emit('updatechange')
                         wrapper_action()
                    }"
      ></receiving_materialcheck_with_materialitem_and_dltCom>
    </div>

    <!--        <receiving_materialCom
                    v-for="(materialDevelItem,,index) in dataList"
                    :key="index"
                    style="border: 1px solid #ddd;
            padding: 5px;
            border-radius: 5px;margin-bottom: 10px;"
                    :props_devel-material-item-dtl-list="materialDevelItem?.detailsList"
                    :props_billingType="formData.billingType"
            ></receiving_materialCom>-->
    <div v-if="!$props?.props_hiddenFooter">
      <div style="display: flex;align-items: flex-start;justify-content: space-between" v-if="!isHidden_billingType">
        <span>暂未开单</span>
        <van-switch v-model="formData.billingType"
                    size="22px"
                    :active-value="5"
                    :inactive-value="1"
                    @change="_value=>{

                    }"
        />
      </div>
      <div
          style="display: flex;align-items: flex-start;justify-content: space-between;margin-top: 5px;margin-bottom: 10px;">
        <span>物料总费用</span>
        <span style="font-size: 14px;"><span
            v-if="watch_sum_materialMoney">{{ toFixedInt(watch_sum_materialMoney) }}</span><span
            v-else>--</span></span>
      </div>
      <div style="display: flex;align-items: flex-start;justify-content: space-between">
        <span>
            <template v-if="formData.billingType!=5">
                <i style="padding-right: 2px;" class="red"
                   v-if="watch_sum_materialMoney>0"
                >*</i>
            </template>
           附件
        </span>
        <uploadImagePlus :fileList="(attachList||[]).filter(item=>item.expendType=='物料报销单据')"
                         :uploadType="$uploadType.file_purchase"
                         ref="uploadImageDom"
                         @deleteFile="(file)=>{
                              deleteFile_group(file)
                             }"
                         @change="files=>{
                                     var attachlist_no=(attachList||[]).filter(item=>item.expendType!='物料报销单据')
                                      attachList=(attachlist_no||[]).concat(files.map(item=>{
                                              item.expendType='物料报销单据'
                                              return  item
                                          }))
                           }">
        </uploadImagePlus>
      </div>
      <div
          style="display: flex;align-items: flex-start;justify-content: space-between;margin-top: 5px;margin-top: 10px;">
        <span>专送总费用</span>
        <span style="font-size: 14px;"><span
            v-if="watch_sum_courierMoney">{{ toFixedInt(watch_sum_courierMoney) }}</span><span
            v-else>--</span></span>
      </div>



      <div
          style="display: flex;align-items: flex-start;justify-content: space-between;margin-top: 5px;margin-top: 10px;"
          v-if="materialReceiving?.id">
        <span desc="未请款中的可请款的部分">可请款</span>
        <span style="font-size: 14px;">{{ toFixedInt(watch_sum_keyibaoxiao) }}</span>
      </div>

      <div
          style="display: flex;align-items: flex-start;justify-content: space-between;margin-top: 5px;margin-top: 10px;"
          v-if="materialReceiving?.id">
        <span>请款中</span>
        <span style="font-size: 14px;">{{ toFixedInt(watch_sum_paystate3) }}</span>
      </div>
      <div
          style="display: flex;align-items: flex-start;justify-content: space-between;margin-top: 5px;margin-top: 10px;"
          v-if="materialReceiving?.id">
        <span>已请款</span>
        <span style="font-size: 14px;">{{ toFixedInt(watch_sum_paystate10) }}</span>
      </div>
<!--      <div
          style="display: flex;align-items: flex-start;justify-content: space-between;margin-top: 5px;margin-top: 10px;">
        <span>可请款</span>
        &lt;!&ndash;        payState{{materialReceiving?.payState}}&ndash;&gt;
        &lt;!&ndash;        watch_sum_keyibaoxiao{{watch_sum_keyibaoxiao}}&ndash;&gt;
        <template v-if="1==1">
          <template v-if="materialReceiving?.payState>1" desc="付款状态：1 待付款 3 请款中  5 部分付款 10 付款完成">
            <span style="font-size: 14px;">{{ toFixedInt(materialReceiving?.eligibleApplyMoney) }}</span>
          </template>
          <template v-else>
              <span style="font-size: 14px;"><span
                  v-if="watch_sum_keyibaoxiao">{{ toFixedInt(watch_sum_keyibaoxiao) }}</span><span
                  v-else>&#45;&#45;</span>
             </span>
          </template>
        </template>


      </div>-->
    </div>
  </div>
</template>
<script>
import * as dev_material_receivingApi from '@/api/dev_material_receiving';

import receiving_materialCom from './receiving_material.vue';
import uploadImagePlus from '@/components/UploadImage/uploadImagePlus.vue';
import materialItem from '@/views/material/dev/developer/developerproductlist/devList/materialList/materialItem.vue';
import { booleanDefault, deepClone, toFixedInt } from '@/utils';
import { lodashEmpty } from '@/utils/lodashUtil';
import { alertConfirm, alertFail, alertWithPayload } from '@/utils/alertUtil';
import receiving_materialDltCom from './receiving_materialDlt.vue';
import { init_form_develmaterialcheck } from '@/domains/develmaterial/develmaterialcheck';
import receiving_materialcheck_with_materialitem_and_dltCom
  from '@/views/components/develmaterial/receiving_materialcheck_with_materialitem_and_dlt.vue';
import * as develMaterialApi from '@/api/material_dev';

function fixedProperty(_dataList) {
  for (let i = 0; i < _dataList.length; i++) {
    if (!_dataList[i]?.develMaterialDtl) {
      _dataList[i].develMaterialDtl = {};
    }
  }

}

export default {
  data() {
    return {
      edit: this.$props.props_edit,
      watch_sum_materialMoney: 0,
      watch_sum_courierMoney: 0,
      toFixedInt,
      attachList: [],
      formData: {
        billingType: 1,
      },
      //mateialDtlList
      checkList: [],
      isvalidate: this.$props.props_isvalidate,
      isdtlarray: this.props_isdtlarray,
      materialReceiving: this.$props.props_materialReceiving,
      isHidden_billingType: false,
      //可报销金额
      watch_sum_keyibaoxiao: 0,
      watch_sum_paystate3: 0,
      watch_sum_paystate10: 0,


    };
  },
  components: {
    receiving_materialcheck_with_materialitem_and_dltCom,
    receiving_materialDltCom,
    materialItem,
    uploadImagePlus,
    receiving_materialCom,
  },
  computed: {
    computed_show_close() {
      if ((typeof this.$props.props_show_close == 'boolean') && !this.$props.props_show_close) {
        return false;
      }
      if (/*编辑是false  不能编辑*/(typeof this.$props.props_edit == 'boolean') && !this.$props.props_edit) {
        console.warn('退出逻辑 不能编辑');
        return false;
      }
      return true;
    },

  },
  props: {
    //如果 物料明细是一个数组
    props_isdtlarray: {
      type: [Boolean], default() {
        return false;
      },
    },
    props_materialReceiving: {
      type: [Object],

    },

    props_edit: {
      type: [Boolean],
      default() {
        return true;
      },
    },
    props_show_close: {
      type: [Boolean],
      default() {
        return true;
      },
    },
    /**
     * @desc 是否开启校验逻辑 默认no
     * @ params
     * */
    props_isvalidate: {
      type: [Boolean],
      default() {
        return false;
      },

    },
    props_hiddenFooter: {
      type: [Boolean],
      default() {
        return false;
      },
    },
  },
  methods: {
    initByDialog(_data) {
      var _dataList = _data?.checkList || [];
      fixedProperty(_dataList);
      this.checkList = _dataList;
      console.log('-> this.checkList', this.checkList);
      this.isvalidate = booleanDefault(_data?.isvalidate, this.$props.props_isvalidate);
      console.log('-> this.isvalidate=bo', this.isvalidate);
      this.edit = booleanDefault(_data?.edit, this.$props.props_edit);

      this.materialReceiving = _data.materialReceiving || this.$props.props_materialReceiving;

      this.isHidden_billingType = booleanDefault(_data?.isHidden_billingType, false);

      this.attachList = _data?.attachList || [];


      this.wrapper_action();

    },
    async deleteFile_group(file) {
      if (file && file.id) {
        var result=await    dev_material_receivingApi.devmateraildelattachf(file && file.id)
        alertWithPayload(result)
      }

    },
    // billing_type         tinyint      not null comment '是否缺单据：1 否 5 是',
    action_computed_billingType() {
      var billingType = 1;
      for (let i = 0; i < this.checkList.length; i++) {
        /*   if (this.dataList[i]?.receivingType == 1/!*物料*!/) {*/
        if (/*物料金额*/this.checkList[i].materialMoney < 0) {
          return 5;
        }
        if (/*物料数量*/this.checkList[i].receivingNum <= 0) {
          return 5;
        }

        if (/*专送大0*/this.checkList[i]?.courierMoney > 0) {
          if (lodashEmpty((this.checkList[i]?.attachList || []).filter(item => item.expendType == '专送'))) {
            return 5;
          }



        }
        /* } else if (this.dataList[i]?.receivingType == 2/!*工艺*!/) {
             for (let j = 0; j < this.dataList[i].secondaryList?.length; j++) {
                 var ignoreListName = ['固色', '洗水'];
                 if (!ignoreListName.includes(this.dataList[i].secondaryList?.[j].processName)) {
                     if (/!*工艺金额*!/this.dataList[i].secondaryList?.[j].processMoney <= 0) {
                         console.log('退出 二次工艺 没哟金额');
                         return 5;
                     }
                 }
                 if (this.dataList[i].secondaryList?.[j].processMoney > 0) {
                     if (lodashEmpty(this.dataList[i].secondaryList?.[j].attachList || [])) {
                         console.log('退出 二次工艺没有专送附件');
                         return 5;
                     }
                 }
             }
         }*/

      }
      // if (/*物料*/this.formData?.receivingType == 1) {
      if(  (this.checkList||[]).filter(item=>item.materialMoney>0).length>0){
        if (lodashEmpty(this.attachList.filter(item => item.expendType == '物料报销单据'))) {
          console.log('退出 物料报销单据 没有附件');
          return 5;
        }
      }

      var sum_money=(this.checkList||0).reduce((total,item)=>{
        return parseFloat(item.materialMoney||0)+parseFloat(total)
      },0)
      if(sum_money<=0/*总金额小于0 资料未齐备*/){
        return 5;
      }


      // }
      /*   if (/!*物料*!/this.formData?.receivingType == 2) {
             if (lodashEmpty(this.attachList.filter(item => item.expendType == '工艺报销单据'))) {
                 console.log('退出 工艺报销单据没有附件');
                 return 5;
             }
         }*/

      return 1;

    },
    //校验物料 如果逻辑是 array
    validate_material_dtlsislist() {
      for (let i = 0; i < this.dataList?.length; i++) {
        for (let j = 0; j < this.dataList?.[i]?.detailsList.length; j++) {
          if (this.dataList?.[i]?.detailsList[j]?.materialCheck?.materialMoney!='0' && !this.dataList?.[i]?.detailsList[j]?.materialCheck?.materialMoney) {
            alertFail('请输入物料金额');
            return false;
          }
          if (!this.dataList?.[i]?.detailsList[j]?.materialCheck?.receivingNum) {
            alertFail('请输入物料数量');
            return false;
          }
          if (this.dataList?.[i]?.detailsList[j]?.materialCheck?.courierMoney > 0) {
            if (lodashEmpty(this.dataList?.[i]?.detailsList[j]?.materialCheck?.attachList || [].filter(item => item.expendType == '专送'))) {
              alertFail(`请上传专送附件`);
              return false;
            }
          }
        }

      }
    },

    async submitByDialog() {
      /*是否开启校验逻辑*/
      if (this.isvalidate) {
        if (this.formData?.billingType != 5) {
          if (this.isdtlarray) {
            var validateresult = this.validate_material_dtlsislist();
            if (!validateresult) {
              return false;
            }
          } else {
            for (let i = 0; i < this.checkList?.length; i++) {
              if (this.checkList?.[i]?.materialMoney!='0' &&!this.checkList?.[i]?.materialMoney) {
                alertFail('请输入物料金额');
                return false;
              }
              if (!this.checkList?.[i]?.receivingNum) {
                alertFail('请输入物料数量');
                return false;
              }
              if (this.checkList?.[i]?.courierMoney > 0) {
                if (lodashEmpty(this.checkList?.[i]?.attachList || [].filter(item => item.expendType == '专送'))) {
                  alertFail(`请上传专送附件`);
                  return false;
                }
              }
            }
          }


          //组的附件
          if (!this.$props.props_hiddenFooter) {
            if(    (this.checkList||[]).filter(item=>item.materialMoney>0) .length>0){
              if (lodashEmpty(this.attachList)) {
                alertFail(`请上传附件`);
                return false;
              }
            }

          }

        }

      }

      if (lodashEmpty(this.checkList)) {
        alertFail('没有明细 请先选择');
        return false;
      }


      var params = {
        ...this.formData,
        attachList: this.attachList || [],
        checkList: this.checkList || [],
        billingType: this.action_computed_billingType(),

      };
      return { success: true, data: deepClone(params) };

    },
    action_watch_sum_materialMoney() {
      var _dataList = this.checkList || [];
      var sum = 0;
      for (let i = 0; i < _dataList.length; i++) {
        var materialMoney = parseFloat(_dataList[i]?.materialMoney);
        sum += materialMoney;
      }
      this.watch_sum_materialMoney = sum;
    },
    action_watch_sum_courierMoney() {
      var _dataList = this.checkList || [];
      var sum = 0;
      for (let i = 0; i < _dataList.length; i++) {
        var materialMoney = parseFloat(_dataList[i]?.courierMoney);
        sum += materialMoney;
      }
      this.watch_sum_courierMoney = sum;
    },
    //可报销 金额
    action_watch_sum_keyibaoxiao() {
      var _dataList = this.checkList || [];
      var sum = 0;
      for (let i = 0; i < _dataList.length; i++) {
        /**
         * 付款状态：1 待付款 3 请款中  5 部分付款 10 付款完成
         */
        if (_dataList[i]?.materialReceivingDtl) {
          if (/*明细是可报销状态*/(_dataList[i].materialReceivingDtl?.payState || 0)<=1 &&
              (_dataList[i].materialReceivingDtl?.expenseType == 5)
          ) {
            var courierMoney = parseFloat(_dataList[i]?.courierMoney);
            var materialMoney = parseFloat(_dataList[i]?.materialMoney);
            sum += (materialMoney + courierMoney);
          }
        }

      }
      this.watch_sum_keyibaoxiao = sum;
    },
    //情况中
    action_watch_sum_paystate3() {
      var _dataList = this.checkList || [];
      var sum = 0;
      for (let i = 0; i < _dataList.length; i++) {
        /**
         * 付款状态：1 待付款 3 请款中  5 部分付款 10 付款完成
         */
        if (_dataList[i]?.materialReceivingDtl) {
          if (/*明细是可报销状态*/(_dataList[i].materialReceivingDtl?.payState || 0) ==3 &&
              (_dataList[i].materialReceivingDtl?.expenseType == 5)
          ) {
            var courierMoney = parseFloat(_dataList[i]?.courierMoney);
            var materialMoney = parseFloat(_dataList[i]?.materialMoney);
            sum += (materialMoney + courierMoney);
          }
        }
      }
      this.watch_sum_paystate3 = sum;
    },
    //请款完成
    action_watch_sum_paystate10() {
      var _dataList = this.checkList || [];
      var sum = 0;
      for (let i = 0; i < _dataList.length; i++) {
        /**
         * 付款状态：1 待付款 3 请款中  5 部分付款 10 付款完成
         */
        if (_dataList[i]?.materialReceivingDtl) {
          if (/*明细是可报销状态*/[5,10].includes(parseInt(( _dataList[i].materialReceivingDtl?.payState || 0) )) &&
              (_dataList[i].materialReceivingDtl?.expenseType == 5)
          ) {
            var courierMoney = parseFloat(_dataList[i]?.courierMoney);
            var materialMoney = parseFloat(_dataList[i]?.materialMoney);
            sum += (materialMoney + courierMoney);
          }
        }
      }
      this.watch_sum_paystate10 = sum;
    },



    wrapper_action() {
      this.action_watch_sum_materialMoney();
      this.action_watch_sum_courierMoney();
      this.action_watch_sum_keyibaoxiao();
      this.action_watch_sum_paystate3()
      this.action_watch_sum_paystate10()
    },
    triggerDeleteDlt(materialDevelItem, index) {
      this.checkList.splice(index, 1);
      this.$emit('deleteOne', materialDevelItem);


    },


  },

};
</script>
